<template>
  <div>
    <el-row>
      <el-col :span="12">
        <h2 style="margin-bottom: 20px">商品管理</h2>
        <!-- 添加商品表单 -->
        <el-form :model="newProduct" @submit.prevent="addProduct">
          <el-form-item label="商品名称">
            <el-input v-model="newProduct.name" placeholder="商品名称" required style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="价&emsp;&emsp;格">
            <el-input v-model.number="newProduct.price" placeholder="价格" required style="width: 300px"></el-input>
          </el-form-item>
          <el-form-item label="上市时间">
            <el-date-picker v-model="newProduct.releaseDate" type="date" placeholder="上市时间" required></el-date-picker>
          </el-form-item>
          <el-form-item label="库&emsp;&emsp;存">
            <el-input-number v-model.number="newProduct.stock" placeholder="库存" required></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="addProduct">添加商品</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <!-- 商品列表 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="product in products" :key="product.id">
        <el-card>
          <h3>{{ product.name }}</h3>
          <p>价格: ¥{{ product.price }}</p>
          <p>上市时间: {{ formatDate(product.releaseDate) }}</p>
          <p>库存: {{ product.stock }}</p>
          <el-button type="primary" @click="editProduct(product)">修改</el-button>
          <el-button type="danger" @click="deleteProduct(product.id)">删除</el-button>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改商品表单 -->
    <el-dialog v-model="editDialogVisible" title="修改商品" style="width: 400px">
      <el-form :model="currentProduct">
        <el-form-item label="商品名称">
          <el-input v-model="currentProduct.name" required></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="currentProduct.price" required></el-input>
        </el-form-item>
        <el-form-item label="上市时间">
          <el-date-picker v-model="currentProduct.releaseDate" type="date" required></el-date-picker>
        </el-form-item>
        <el-form-item label="库存">
          <el-input-number v-model.number="currentProduct.stock" required></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="updateProduct">确认修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import 'element-plus/dist/index.css';
import { ElMessage } from 'element-plus';

const products = ref([]);
const newProduct = ref({ name: '', price: 0, releaseDate: '', stock: 0 });
const currentProduct = ref({ name: '', price: 0, releaseDate: '', stock: 0 });
const editDialogVisible = ref(false);

// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 获取商品列表
const fetchProducts = async () => {
  try {
    const response = await axios.get('http://localhost:3000/products');
    products.value = response.data;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    console.error('Error fetching products:', error);
  }
};

onMounted(fetchProducts);

// 添加商品
const addProduct = async () => {
  try {
    const product = { ...newProduct.value, price: Number(newProduct.value.price), stock: Number(newProduct.value.stock) };
    product.releaseDate = product.releaseDate instanceof Date ? formatDate(product.releaseDate) : product.releaseDate;
    await axios.post('http://localhost:3000/products', product);
    ElMessage.success('商品添加成功');
    await fetchProducts();
    resetNewProduct();
  } catch (error) {
    ElMessage.error('商品添加失败');
    console.error('Error adding product:', error);
  }
};

// 删除商品
const deleteProduct = async (id) => {
  try {
    await axios.delete(`http://localhost:3000/products/${id}`);
    ElMessage.success('商品删除成功');
    await fetchProducts();
  } catch (error) {
    ElMessage.error('商品删除失败');
    console.error('Error deleting product:', error);
  }
};

// 设置当前编辑的商品
const editProduct = (product) => {
  currentProduct.value = { ...product, releaseDate: new Date(product.releaseDate) };
  editDialogVisible.value = true;
};

// 更新商品
const updateProduct = async () => {
  try {
    const id = currentProduct.value.id;
    const product = { ...currentProduct.value, price: Number(currentProduct.value.price), stock: Number(currentProduct.value.stock) };
    product.releaseDate = product.releaseDate instanceof Date ? formatDate(product.releaseDate) : product.releaseDate;
    await axios.put(`http://localhost:3000/products/${id}`, product);
    ElMessage.success('商品修改成功');
    await fetchProducts();
    closeEditDialog();
  } catch (error) {
    ElMessage.error('商品修改失败');
    console.error('Error updating product:', error);
  }
};

// 关闭编辑对话框
const closeEditDialog = () => {
  editDialogVisible.value = false;
  resetCurrentProduct();
};

// 重置新商品表单
const resetNewProduct = () => {
  newProduct.value = { name: '', price: 0, releaseDate: '', stock: 0 };
};

// 重置当前商品
const resetCurrentProduct = () => {
  currentProduct.value = { name: '', price: 0, releaseDate: '', stock: 0 };
};
</script>


<style scoped>
.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  padding: 16px;
}
.el-card{
  margin-bottom: 10px;

}

.product-card {
  border: 1px solid #ccc;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  background-color: #f9f9f9;
  transition: transform 0.2s;
}

.product-card:hover {
  transform: scale(1.05);
}

form {
  margin-bottom: 16px;
}

form input {
  margin-right: 8px;
  padding: 8px;
}

form button {
  padding: 8px 16px;
}
p{
  margin: 5px;
}
</style>